<?php
/**
 * [YIZHIKEJI System] Copyright (c) 2014 yz929.cn
 * YIZHIKEJI is NOT a free software, it under the license terms, visited http://www.yz929.cn/ for more details.
 */

defined('IN_IA') or exit('Access Denied');
$_W['page']['title'] = '添加/编辑公众号';
$uniacid = intval($_GPC['uniacid']);
if (isset($_GPC['uniacid'])) {
    $wechat = pdo_fetch("SELECT * FROM " . tablename("wechat_account") . " WHERE id = '{$uniacid}'");
}
if (empty($_W['isfounder'])) {
    message('管理员才有这个权限');
}
if (checksubmit('submit')) {
    $wechat = array();
    $wechat['name'] = trim($_GPC['cname']);
    $wechat['account'] = trim($_GPC['account']);
    $wechat['original'] = trim($_GPC['original']);
    $wechat['key'] = trim($_GPC['key']);
    $wechat['secret'] = trim($_GPC['secret']);
    $wechat['encodingaeskey'] = trim($_GPC['encodingaeskey']);
    $wechat['token'] = trim($_GPC['token']);
    $wechat['description'] = trim($_GPC['description']);

//    if (file_exists(IA_ROOT . '/attachment/qrcode_wechat_' . $wechat['uniacid'] . '.jpg')) {
//        file_move(IA_ROOT . '/attachment/qrcode_wechat_' . $wechat['uniacid'] . '.jpg', IA_ROOT . '/attachment/qrcode_wechat_' . $wechat['uniacid'] . '.jpg');
//        $result = file_remote_upload('qrcode_wechat_' . $wechat['uniacid'] . '.jpg');
//        if (!is_error($result) && $result !== false) {
//            file_delete('qrcode_wechat_' . $wechat['uniacid'] . '.jpg');
//        }
//    }
//    if (file_exists(IA_ROOT . '/attachment/headimg_wechat_' . $wechat['uniacid'] . '.jpg')) {
//        file_move(IA_ROOT . '/attachment/headimg_wechat_' . $wechat['uniacid'] . '.jpg', IA_ROOT . '/attachment/headimg_wechat_' . $wechat['uniacid'] . '.jpg');
//        $result = file_remote_upload('headimg_wechat_' . $wechat['uniacid'] . '.jpg');
//        if (!is_error($result) && $result !== false) {
//            file_delete('headimg_wechat_' . $wechat['uniacid'] . '.jpg');
//        }
//    }
    if (empty($wechat['name'])) {
        message('公众号名称必须填写');
    }
    if (empty($uniacid)) {
        if (!pdo_insert('wechat_account', $wechat)) {
            message('添加公众号失败');
        }
        $uniacid = pdo_insertid();
    } else {
        pdo_update('wechat_account', $wechat);
    }
    load()->func('file');
    if (!empty($_FILES['qrcode']['tmp_name'])) {
        $_W['uploadsetting'] = array();
        $_W['uploadsetting']['image']['folder'] = '';
        $_W['uploadsetting']['image']['extentions'] = array('jpg');
        $_W['uploadsetting']['image']['limit'] = $_W['config']['upload']['image']['limit'];
        $upload = file_upload($_FILES['qrcode'], 'image', "qrcode_wechat_{$uniacid}");
        if(is_array($upload)) {
            $result = file_remote_upload($upload['path']);
            if (!is_error($result) && $result !== false) {
                file_delete($upload['path']);
            }
        }
    }

    message('更新公众号信息成功！', url('account/official-account'), 'success');
}
template('account/post-step');